<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>玩转JAVA正则2 | 静待花开</title><meta name="author" content="brad 随风起舞"><meta name="copyright" content="brad 随风起舞"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="java 正则类在Java中，当我们处理复杂的项目时，会遇到许多输入，这些输入通常需要代码才能使文本与模式相等。 正是在电子邮件标头验证，文本搜索以及根据常规文本创建自定义文本等中经常使用此功能。 Java String 方法在进入java.util.regex包之前，让我们看一下java String类提供的一些使用正则表达式的方法。 这些方法可用于较少的简单验证。 但是，如果我们要经常使用正则">
<meta property="og:type" content="article">
<meta property="og:title" content="玩转JAVA正则2">
<meta property="og:url" content="https://zhangbo4881820.gitee.io/myblog/posts/42642/index.html">
<meta property="og:site_name" content="静待花开">
<meta property="og:description" content="java 正则类在Java中，当我们处理复杂的项目时，会遇到许多输入，这些输入通常需要代码才能使文本与模式相等。 正是在电子邮件标头验证，文本搜索以及根据常规文本创建自定义文本等中经常使用此功能。 Java String 方法在进入java.util.regex包之前，让我们看一下java String类提供的一些使用正则表达式的方法。 这些方法可用于较少的简单验证。 但是，如果我们要经常使用正则">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2019-10-31T01:46:05.000Z">
<meta property="article:modified_time" content="2023-09-07T09:44:01.882Z">
<meta property="article:author" content="brad 随风起舞">
<meta property="article:tag" content="reg">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/myblog/img/favicon.png"><link rel="canonical" href="https://zhangbo4881820.gitee.io/myblog/posts/42642/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/myblog/css/index.css"><link rel="stylesheet" href="/myblog/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="/myblog/css/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/myblog/',
  algolia: undefined,
  localSearch: {"path":"/myblog/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '玩转JAVA正则2',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2023-09-07 17:44:01'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 7.0.0-rc2"><link rel="alternate" href="/myblog/atom.xml" title="静待花开" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/myblog/archives/"><div class="headline">文章</div><div class="length-num">57</div></a><a href="/myblog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a><a href="/myblog/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/myblog/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/myblog/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/myblog/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/myblog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/myblog/" title="静待花开"><span class="site-name">静待花开</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/myblog/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/myblog/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/myblog/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/myblog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">玩转JAVA正则2</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-10-31T01:46:05.000Z" title="发表于 2019-10-31 09:46:05">2019-10-31</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-09-07T09:44:01.882Z" title="更新于 2023-09-07 17:44:01">2023-09-07</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/myblog/categories/%E6%AD%A3%E5%88%99/">正则</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="玩转JAVA正则2"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><h2 id="java-正则类"><a href="#java-正则类" class="headerlink" title="java 正则类"></a>java 正则类</h2><p>在Java中，当我们处理复杂的项目时，会遇到许多输入，这些输入通常需要代码才能使文本与模式相等。 正是在电子邮件标头验证，文本搜索以及根据常规文本创建自定义文本等中经常使用此功能。</p>
<h3 id="Java-String-方法"><a href="#Java-String-方法" class="headerlink" title="Java String 方法"></a>Java String 方法</h3><p>在进入java.util.regex包之前，让我们看一下java String类提供的一些使用正则表达式的方法。 这些方法可用于较少的简单验证。 但是，如果我们要经常使用正则表达式，那么这些方法将带来性能开销</p>
<ol>
<li><p><strong>matches() 方法</strong><br> sampleString.matches（“ regex”）返回true或false取决于正则表达式是否可以完全匹配字符串。 要记住的重要一点是，String.matches（）仅在可以匹配整个字符串时才返回true。</p>
 <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">	public class DemoForStringMatches &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        // 定义一个匹配模式                            </span><br><span class="line">        String regex = &quot;.@.&quot;;</span><br><span class="line">        // 尝试将需要字符串与正则表达式匹配                           </span><br><span class="line">        DemoForStringMatches.matchIt(&quot;a@k&quot;, regex);</span><br><span class="line">        DemoForStringMatches.matchIt(&quot;webmaster@jdojo.com&quot;, regex);</span><br><span class="line">        DemoForStringMatches.matchIt(&quot;r@j&quot;, regex);</span><br><span class="line">        DemoForStringMatches.matchIt(&quot;a%N&quot;, regex);</span><br><span class="line">        DemoForStringMatches.matchIt(&quot;.@.&quot;, regex);</span><br><span class="line">    &#125;</span><br><span class="line">    public static void matchIt(String str, String regex) &#123;</span><br><span class="line">//        测试模式匹配</span><br><span class="line">        if (str.matches(regex)) &#123;</span><br><span class="line">//            使用String类的匹配方法</span><br><span class="line">            System.out.println(str + &quot;匹配这个模式:&quot; + regex);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            System.out.println(str + &quot;不匹配这个模式:&quot; + regex);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>output:</strong></p>
<pre><code> a@k匹配这个模式:.@.
 webmaster@jdojo.com不匹配这个模式:.@.
 r@j匹配这个模式:.@.
 a%N不匹配这个模式:.@.
 .@.匹配这个模式:.@.	
</code></pre>
</li>
<li><p><strong>replaceAll()方法</strong><br> sampleString.replaceAll(“regex”, “replacement”) 用你定义的‘replacement’替换所有正则表达式模式匹配的字符串。所有匹配的字符串都会被替换。</p>
 <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">	public class DemoForReplaceAll &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        // 准备一个正则表达式                           </span><br><span class="line">        String regex = &quot;.@.&quot;;</span><br><span class="line">        String replacementString = &quot;***&quot;;</span><br><span class="line">        // 匹配正则表达式 进行替换                           </span><br><span class="line">        DemoForReplaceAll.replaceMatch(&quot;webd@koj&quot;, regex, replacementString);</span><br><span class="line">    &#125;</span><br><span class="line">    public static void replaceMatch(String str, String regex, String replacementString) &#123;</span><br><span class="line">        // 测试替换                           </span><br><span class="line">        String newStr = str.replaceAll(regex, replacementString);</span><br><span class="line">        System.out.println(regex + &quot; replaced &quot; + newStr);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>output</strong></p>
<pre><code> .@. replaced web***oj
</code></pre>
</li>
<li><p><strong>replaceFirst()方法</strong><br> The replaceFirst()方法用’replacementString’替换第一次匹配的字符串。替换后返回一个新的字符串</p>
 <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">public static void main(String[] args) &#123;</span><br><span class="line">    String regex = &quot;.@.&quot;;</span><br><span class="line">    String replacementString = &quot;***&quot;;</span><br><span class="line">    DemoForReplaceFirst.replaceMatch(&quot;A@BandH@G&quot;, regex, replacementString);</span><br><span class="line">&#125;</span><br><span class="line">public static void replaceMatch(String str, String regex, String replacementString) &#123;</span><br><span class="line">    String newStr = str.replaceFirst(regex, replacementString);</span><br><span class="line">    System.out.println(regex + &quot; replaced &quot; + newStr);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>output</strong></p>
<pre><code> .@. replaced ***andH@G
</code></pre>
</li>
<li><p><strong>split()方法</strong><br> sampleString.split(“regex”) 是在每个正则匹配的String处来分割字符串。这个方法的返回将是一个String数组，这个String数组中的元素就是在两个正则匹配之间的原生String</p>
 <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">public static void main(String[] args) &#123;</span><br><span class="line">    String str = &quot;one-two-three&quot;;</span><br><span class="line">    String[] temp; /* delimiter */</span><br><span class="line">    String delimiter = &quot;-&quot;;</span><br><span class="line">    temp = str.split(delimiter); /* print substrings */</span><br><span class="line">    for (int i = 0; i &lt; temp.length; i++)</span><br><span class="line">        System.out.println(temp[i]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>output:</strong></p>
<pre><code> one
 two
 three
</code></pre>
</li>
</ol>
<h3 id="Java-util-Regex"><a href="#Java-util-Regex" class="headerlink" title="Java util Regex"></a>Java util Regex</h3><p>java.util.regex 软件包主要包含以下三个类：（来源：Oracle Java文档，<a href="http://www.docs.oracle.com)/">www.docs.oracle.com）</a></p>
<ul>
<li><p><strong>Pattern Class:</strong><br>  Pattern对象是正则表达式的编译表示形式。Pattern类不提供公共构造函数。要创建模式，必须首先调用其公  共静态编译方法之一，然后再返回Pattern对象。这些方法接受正则表达式作为第一个参数。</p>
</li>
<li><p><strong>Matcher Class:</strong><br>  Matcher对象是解释模式并针对输入字符串执行匹配操作的引擎。与Pattern类一样，Matcher没有定义公共构造函数。<br>  您可以通过在Pattern对象上调用matcher方法来获得Matcher对象</p>
</li>
<li><p><strong>PatternSyntaxException:</strong><br>  PatternSyntaxException对象是未经检查的异常，表示正则表达式模式中的语法错误</p>
</li>
</ul>
<p><strong>Sample:</strong></p>
<pre><code><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"> public static void main(String[] args) &#123;</span><br><span class="line"></span><br><span class="line">    Pattern pattern = Pattern.compile(&quot;.ab.&quot;);</span><br><span class="line">    Matcher matcher = pattern.matcher(&quot;WabY&quot;);</span><br><span class="line">    Matcher m1 = pattern.matcher(&quot;WxxY&quot;);</span><br><span class="line">    System.out.println(&quot;输入字符串与正则匹配 - &quot; + matcher.matches());</span><br><span class="line">    System.out.println(&quot;输入字符串与正则匹配 - &quot; + m1.matches());</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</code></pre>
<p><strong>output:</strong></p>
<pre><code>输入字符串与正则匹配 - true
输入字符串与正则匹配 - false
</code></pre>
<p><strong>例子解析</strong></p>
<p>在上面这个例子中，<code>Pattern</code> 类中的 <code>compile()</code> 方法被用作去编译一个需要被验证的正则表达式，然后编译验证通过后使用<br><code>pattern.matcher()</code> 方法去与被编译的正则表达式进行验证</p>
<p>在上面的例子中正则模板使用的是 <code>.ab.</code> ,这表达式的意思是在 <strong>ab</strong> 之前和之后都有一个字符，并且 <strong>ab</strong> 应该在这两个字符中间。遵循此指定的正则模板的任何字符串都将返回true以进行匹配。因此，第一个模板 “WabY” 是匹配的，且返回true,第二个模板 “WxxY” 是不匹配的，且返回false</p>
<h3 id="Pattern-Class-Methods"><a href="#Pattern-Class-Methods" class="headerlink" title="Pattern Class Methods"></a>Pattern Class Methods</h3><h4 id="Pattern-compile"><a href="#Pattern-compile" class="headerlink" title="Pattern.compile()"></a>Pattern.compile()</h4><p>如果我们需要频繁的执行某个正则表达式的搜索，或者在执行搜索时我们需要额外的添加一些参数,(例如忽略大小写搜索)<br>那么我们就使用 <strong>Pattern.compile()</strong> 方法去编译正则表达式</p>
<p>下面是忽略大小写的使用方法：<br><strong>String content &#x3D; “this is my regex”;</strong><br>*<em>String patternString &#x3D; “.<em>reGeX”;</em></em><br><strong>Pattern pattern &#x3D; Pattern.compile(patternString,Pattern.CASE_INSENSITIVE);</strong></p>
<p>上面的例子中使用到了模板标志，下面就列出一下其他的模板标志:</p>
<table>
<thead>
<tr>
<th>标志(flags)</th>
<th>解释(explanation)</th>
</tr>
</thead>
<tbody><tr>
<td>Pattern.CANON_EQ</td>
<td>用于启用规范对等。仅当存在规范分解匹配时才需要匹配两个表达式时，才使用此标志。</td>
</tr>
<tr>
<td>Pattern.CASE_INSENSITIVE</td>
<td>不考虑大小写进行搜索匹配</td>
</tr>
<tr>
<td>Pattern.COMMENTS</td>
<td>在模式中允许空格和注释。通过使用此标志，可以在表达式中忽略以＃开头的空格和注释。</td>
</tr>
<tr>
<td>Pattern.DOTALL</td>
<td>用于启用dotall模式。在此模式下，“.”代表任何字符，包括行终止符</td>
</tr>
<tr>
<td>Pattern.LITERAL</td>
<td>用于启用给定表达式的文字解析。使用此标志时，用于验证的整个表达式将被视为文字字符，而不是整个字符串</td>
</tr>
<tr>
<td>Pattern.MULTILINE</td>
<td>用于启用多行模式。默认情况下，元字符^和$与表达式的开头和结尾匹配。但是，当使用此标志时，这些字符在行终止符（即.）前后匹配“.”符号。</td>
</tr>
<tr>
<td>Pattern.UNICODE_CASE</td>
<td>当我们要比较Unicode大小写时（通常只比较ASCII字符），此标志与CASE_INSENSITIVE标志结合使用</td>
</tr>
<tr>
<td>Pattern.UNIX_LINES</td>
<td>该标志启用Unix行模式。在此模式下,“&#x2F;n”被视为行终止符,而不是“.”字符。</td>
</tr>
</tbody></table>
<p>有的flag能够使用正则表达式作为一个字符插入,他们是相同的意思,如下表展示：</p>
<table>
<thead>
<tr>
<th>标志(flag)</th>
<th>与之相等的插入字符</th>
</tr>
</thead>
<tbody><tr>
<td>Pattern.CANON_EQ</td>
<td>None</td>
</tr>
<tr>
<td>Pattern.CASE_INSENSITIVE</td>
<td>(?i)</td>
</tr>
<tr>
<td>Pattern.COMMENTS</td>
<td>(?x)</td>
</tr>
<tr>
<td>Pattern.MULTILINE</td>
<td>(?m)</td>
</tr>
<tr>
<td>Pattern.DOTALL</td>
<td>(?s)</td>
</tr>
<tr>
<td>Pattern.LITERAL</td>
<td>None</td>
</tr>
<tr>
<td>Pattern.UNICODE_CASE</td>
<td>(?u)</td>
</tr>
<tr>
<td>Pattern.UNIX_LINES</td>
<td>(?d)</td>
</tr>
</tbody></table>
<h4 id="Pattern-matches"><a href="#Pattern-matches" class="headerlink" title="Pattern.matches()"></a>Pattern.matches()</h4><p>很简单的方法·就返回一个布尔值,看是否匹配。看下面的代码就知道咋用了。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">String content = &quot;This is my tutorial sample&quot;;</span><br><span class="line">String patternString = &quot;.*tutorial.*&quot;;</span><br><span class="line">boolean isMatch = Pattern.matches(patternString, content);</span><br><span class="line">System.out.println(&quot;The text contains &#x27;tutorial&#x27;? &quot; + isMatch);</span><br></pre></td></tr></table></figure>

<p><strong>output:</strong></p>
<pre><code>The text contains &#39;tutorial&#39;? true
</code></pre>
<h4 id="Pattern-matcher-方法"><a href="#Pattern-matcher-方法" class="headerlink" title="Pattern.matcher() 方法"></a>Pattern.matcher() 方法</h4><p>使用这个方法后返回 <code>Matcher</code> 类实例,当执行多次验证或者当分组被用到的时候可以使用这个方法</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">String content = &quot;This is my regex sample&quot;;</span><br><span class="line">String patternString = &quot;.*rEgeX.*&quot;;</span><br><span class="line">Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);</span><br><span class="line">Matcher matcher = pattern.matcher(content);</span><br><span class="line">boolean isMatched = matcher.matches();</span><br><span class="line">System.out.println(&quot;Is it a Match?&quot; + isMatched);</span><br></pre></td></tr></table></figure>

<p><strong>output:</strong></p>
<pre><code>Is it a Match?true
</code></pre>
<h4 id="Pattern-split-方法"><a href="#Pattern-split-方法" class="headerlink" title="Pattern.split() 方法"></a>Pattern.split() 方法</h4><p>这个方法根据定界符(正则模式中指定的)分割一个被传入的文本成多个字符串。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">String text = &quot;ItIsRegexSample.ItISProvidedByMe&quot;;</span><br><span class="line">   // 定界符                           </span><br><span class="line">   String patternString = &quot;is&quot;;</span><br><span class="line">   Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);</span><br><span class="line">   String[] myStrings = pattern.split(text);</span><br><span class="line">   for (String temp : myStrings) &#123;</span><br><span class="line"></span><br><span class="line">       System.out.println(temp);</span><br><span class="line">   &#125;</span><br><span class="line">   System.out.println(&quot;分割后的字符串个数:&quot;+myStrings.length);</span><br></pre></td></tr></table></figure>
<p><strong>output:</strong></p>
<pre><code>It
RegexSample.It
ProvidedByMe
分割后的字符串个数:3
</code></pre>
<h3 id="Matcher-Class-Methods"><a href="#Matcher-Class-Methods" class="headerlink" title="Matcher Class Methods"></a>Matcher Class Methods</h3><h4 id="创建一个-Matcher-实例"><a href="#创建一个-Matcher-实例" class="headerlink" title="创建一个 Matcher 实例"></a>创建一个 Matcher 实例</h4><p>在 pattern 部分已经使用过，不在具体说。</p>
<p><strong>String content &#x3D; “Some text”</strong><br>*<em>String patternString &#x3D; “.<em>somestring.</em>“;</em>*<br><strong>Pattern pattern &#x3D; Pattern.compile(patternString);</strong><br><code>Matcher matcher = pattern.matcher(content);</code></p>
<h4 id="Matches-方法"><a href="#Matches-方法" class="headerlink" title="Matches() 方法"></a>Matches() 方法</h4><p>在 pattern 部分已经使用过，不在具体说。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);</span><br><span class="line">Matcher matcher = pattern.matcher(content);         </span><br><span class="line">boolean isMatched = matcher.matches();</span><br></pre></td></tr></table></figure>

<h4 id="lookingAt-方法"><a href="#lookingAt-方法" class="headerlink" title="lookingAt() 方法"></a>lookingAt() 方法</h4><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">String REGEX = &quot;Saa&quot;;</span><br><span class="line">String INPUT = &quot;SaaaaaaaS&quot;; </span><br><span class="line">Pattern pattern = Pattern.compile(REGEX);</span><br><span class="line">Matcher matcher = pattern.matcher(INPUT);                      </span><br><span class="line">System.out.println(&quot;Current REGEX is: &quot;+REGEX);</span><br><span class="line">System.out.println(&quot;Current INPUT is: &quot;+INPUT);</span><br><span class="line">System.out.println(&quot;lookingAt(): &quot;+matcher.lookingAt());</span><br><span class="line">System.out.println(&quot;matches(): &quot;+matcher.matches());</span><br></pre></td></tr></table></figure>

<p><strong>output:</strong></p>
<pre><code>Current REGEX is: Saa 
Current INPUT is: SaaaaaaaS 
lookingAt(): true 
matches(): false
</code></pre>
<p><strong>解析:</strong><br>为什么 <code>lookingAt()</code> 返回true,而 <code>matcher()</code> 返回false,这是因为matcher匹配的是整个字符串所以不匹配，<br>而lookingAt()他仅仅是从起始位开始比较匹配到了后面的字符串就不会比较了，所以返回true</p>
<h4 id="find-方法"><a href="#find-方法" class="headerlink" title="find() 方法"></a>find() 方法</h4><p>此方法用于搜索文本中正则表达式的出现。当我们在大量数据中搜索字符串的多次出现时，经常使用它。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">String REGEX = &quot;too&quot;;</span><br><span class="line">   String INPUT = &quot;too&quot;;</span><br><span class="line">   Pattern p = Pattern.compile(REGEX);</span><br><span class="line">   Matcher m = p.matcher(INPUT);</span><br><span class="line">   while (m.find()) &#123;</span><br><span class="line">       System.out.println(&quot;start(): &quot; + m.start());</span><br><span class="line">       System.out.println(&quot;end(): &quot; + m.end());</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p><strong>output:</strong></p>
<pre><code>start(): 0
end(): 3
</code></pre>
<p>这个方法还可以传入组号索引，这里不演示！</p>
<h4 id="appendReplacement-StringBuffer-sb-String-replacement"><a href="#appendReplacement-StringBuffer-sb-String-replacement" class="headerlink" title="appendReplacement(StringBuffer sb,String replacement)"></a>appendReplacement(StringBuffer sb,String replacement)</h4><p>它从输入序列读取字符,从追加位置开始,然后将它们附加到给定的字符串缓冲区(sb)之后,它将给定的替换字符串(replacement)附加到字符串缓冲区以创建新文本</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Pattern p = Pattern.compile(&quot;dog&quot;);</span><br><span class="line">      Matcher m = p.matcher(&quot;one dog two dogs in the house&quot;);</span><br><span class="line">      StringBuffer sb = new StringBuffer();</span><br><span class="line">      while (m.find()) &#123;</span><br><span class="line">          m.appendReplacement(sb, &quot;rabbit&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      System.out.println(sb.toString());</span><br><span class="line">      m.appendTail(sb);</span><br><span class="line">      System.out.println(sb.toString());</span><br></pre></td></tr></table></figure>

<p><strong>output:</strong></p>
<pre><code>one rabbit two rabbit
one rabbit two rabbits in the house
</code></pre>
<h4 id="appendTail-StringBuffer-sb"><a href="#appendTail-StringBuffer-sb" class="headerlink" title="appendTail(StringBuffer sb)"></a>appendTail(StringBuffer sb)</h4><p>这个方法和<code>appendReplacement</code>这个方法结合使用，在替换后用以形成新的字符串</p>
<h4 id="replaceAll-String-replacement"><a href="#replaceAll-String-replacement" class="headerlink" title="replaceAll(String replacement)"></a>replaceAll(String replacement)</h4><p>这方法就是把匹配到的所有的字符串替换成指定的replacement</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">String input = &quot;aaahorsebbbhorseccchorse&quot;;</span><br><span class="line"> String patternString = &quot;horse&quot;;</span><br><span class="line"> String output=&quot;&quot;;</span><br><span class="line"> Pattern p = Pattern.compile(patternString);</span><br><span class="line"> Matcher m = p.matcher(input);</span><br><span class="line"> output = m.replaceAll(&quot;dog&quot;);</span><br><span class="line"> System.out.println(&quot;Input:&quot;+input);</span><br><span class="line"> System.out.println(&quot;Output:&quot;+output);</span><br></pre></td></tr></table></figure>

<p><strong>output:</strong></p>
<pre><code>Input:aaahorsebbbhorseccchorse
Output:aaadogbbbdogcccdog
</code></pre>
<h4 id="replaceFirst-String-replacement"><a href="#replaceFirst-String-replacement" class="headerlink" title="replaceFirst(String replacement)"></a>replaceFirst(String replacement)</h4><p>这个就是匹配到的第一个子集用指定的replacement替换掉</p>
<h4 id="PatternSyntaxException"><a href="#PatternSyntaxException" class="headerlink" title="PatternSyntaxException"></a>PatternSyntaxException</h4><p>没啥好说的·用idea 调一下就知道了。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://zhangbo4881820.gitee.io/myblog">brad 随风起舞</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhangbo4881820.gitee.io/myblog/posts/42642/">https://zhangbo4881820.gitee.io/myblog/posts/42642/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhangbo4881820.gitee.io/myblog" target="_blank">静待花开</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/myblog/tags/reg/">reg</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/myblog/posts/45226/" title="全栈开发(AngularJS原理)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">全栈开发(AngularJS原理)</div></div></a></div><div class="next-post pull-right"><a href="/myblog/posts/21435/" title="玩转JAVA正则"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">玩转JAVA正则</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/myblog/posts/21435/" title="玩转JAVA正则"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-30</div><div class="title">玩转JAVA正则</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/myblog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">brad 随风起舞</div><div class="author-info__description">有些事情需要一辈子的沉淀</div></div><div class="card-info-data site-data is-center"><a href="/myblog/archives/"><div class="headline">文章</div><div class="length-num">57</div></a><a href="/myblog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a><a href="/myblog/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/xxxxx" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:xxxxxx@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#java-%E6%AD%A3%E5%88%99%E7%B1%BB"><span class="toc-number">1.</span> <span class="toc-text">java 正则类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Java-String-%E6%96%B9%E6%B3%95"><span class="toc-number">1.1.</span> <span class="toc-text">Java String 方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Java-util-Regex"><span class="toc-number">1.2.</span> <span class="toc-text">Java util Regex</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Pattern-Class-Methods"><span class="toc-number">1.3.</span> <span class="toc-text">Pattern Class Methods</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Pattern-compile"><span class="toc-number">1.3.1.</span> <span class="toc-text">Pattern.compile()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Pattern-matches"><span class="toc-number">1.3.2.</span> <span class="toc-text">Pattern.matches()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Pattern-matcher-%E6%96%B9%E6%B3%95"><span class="toc-number">1.3.3.</span> <span class="toc-text">Pattern.matcher() 方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Pattern-split-%E6%96%B9%E6%B3%95"><span class="toc-number">1.3.4.</span> <span class="toc-text">Pattern.split() 方法</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Matcher-Class-Methods"><span class="toc-number">1.4.</span> <span class="toc-text">Matcher Class Methods</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA-Matcher-%E5%AE%9E%E4%BE%8B"><span class="toc-number">1.4.1.</span> <span class="toc-text">创建一个 Matcher 实例</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Matches-%E6%96%B9%E6%B3%95"><span class="toc-number">1.4.2.</span> <span class="toc-text">Matches() 方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#lookingAt-%E6%96%B9%E6%B3%95"><span class="toc-number">1.4.3.</span> <span class="toc-text">lookingAt() 方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#find-%E6%96%B9%E6%B3%95"><span class="toc-number">1.4.4.</span> <span class="toc-text">find() 方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#appendReplacement-StringBuffer-sb-String-replacement"><span class="toc-number">1.4.5.</span> <span class="toc-text">appendReplacement(StringBuffer sb,String replacement)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#appendTail-StringBuffer-sb"><span class="toc-number">1.4.6.</span> <span class="toc-text">appendTail(StringBuffer sb)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#replaceAll-String-replacement"><span class="toc-number">1.4.7.</span> <span class="toc-text">replaceAll(String replacement)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#replaceFirst-String-replacement"><span class="toc-number">1.4.8.</span> <span class="toc-text">replaceFirst(String replacement)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#PatternSyntaxException"><span class="toc-number">1.4.9.</span> <span class="toc-text">PatternSyntaxException</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/15695/" title="jenkins（1）">jenkins（1）</a><time datetime="2023-09-14T02:17:44.000Z" title="发表于 2023-09-14 10:17:44">2023-09-14</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/22012/" title="wsl的Ubuntu子系统（1）">wsl的Ubuntu子系统（1）</a><time datetime="2023-09-13T08:42:19.000Z" title="发表于 2023-09-13 16:42:19">2023-09-13</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/30302/" title="effective-java-(接口优于抽象类)">effective-java-(接口优于抽象类)</a><time datetime="2023-09-12T08:12:48.000Z" title="发表于 2023-09-12 16:12:48">2023-09-12</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/9473/" title="effective-java(创建和销毁对象--组合的形式优于继承)">effective-java(创建和销毁对象--组合的形式优于继承)</a><time datetime="2023-09-11T08:23:19.000Z" title="发表于 2023-09-11 16:23:19">2023-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/16107/" title="Hello World">Hello World</a><time datetime="2023-09-07T09:44:01.910Z" title="发表于 2023-09-07 17:44:01">2023-09-07</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By brad 随风起舞</div><div class="framework-info"><span>框架 </span><a href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/myblog/js/utils.js"></script><script src="/myblog/js/main.js"></script><script src="/myblog/js/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/myblog/js/search/local-search.js"></script></div></div></body></html>